<template>
  <div class="batch-actions">
    <el-card class="app-card">
      <template #header>
        <div class="card-header">
          <span>批量操作</span>
        </div>
      </template>
      
      <el-tabs>
        <el-tab-pane label="批量打开网页">
          <div class="tab-content">
            <el-form label-position="top">
              <el-form-item label="网页URL">
                <el-input
                  v-model="urlsInput"
                  type="textarea"
                  :rows="4"
                  placeholder="请输入URL，每行一个"
                />
                <div class="form-hint">支持HTTP和HTTPS协议，每行输入一个网址</div>
              </el-form-item>
              
              <el-form-item>
                <div class="quick-sites">
                  <el-button 
                    v-for="site in quickSites" 
                    :key="site.name" 
                    size="small" 
                    @click="addQuickSite(site.url)"
                  >
                    {{ site.name }}
                  </el-button>
                </div>
              </el-form-item>
              
              <el-form-item>
                <el-button 
                  type="primary" 
                  :disabled="!selectedWindows.length || !hasValidUrls" 
                  :loading="executing" 
                  @click="openWebpages"
                >
                  <el-icon><i-ep-link /></el-icon>
                  在选中窗口打开
                </el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="批量文本输入">
          <div class="tab-content">
            <el-form label-position="top">
              <el-form-item>
                <el-radio-group v-model="inputMode">
                  <el-radio :label="'text'">指定文本</el-radio>
                  <el-radio :label="'random'">随机数字</el-radio>
                </el-radio-group>
              </el-form-item>
              
              <template v-if="inputMode === 'text'">
                <el-form-item label="输入文本">
                  <el-input
                    v-model="inputText"
                    type="textarea"
                    :rows="2"
                    placeholder="请输入要批量输入的文本"
                  />
                </el-form-item>
              </template>
              
              <template v-else>
                <el-form-item label="随机数字设置">
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-form-item label="最小值">
                        <el-input-number v-model="randomMin" :min="0" :max="10000" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="最大值">
                        <el-input-number v-model="randomMax" :min="0" :max="10000" />
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form-item>
              </template>
              
              <el-form-item>
                <el-checkbox v-model="delayInput">延迟输入(每个窗口间隔1秒)</el-checkbox>
              </el-form-item>
              
              <el-form-item>
                <el-button 
                  type="primary" 
                  :disabled="!selectedWindows.length || !canExecuteInput" 
                  :loading="executing" 
                  @click="executeTextInput"
                >
                  <el-icon><i-ep-edit /></el-icon>
                  执行文本输入
                </el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>
        
        <el-tab-pane label="标签页管理">
          <div class="tab-content">
            <el-form label-position="top">
              <el-form-item>
                <el-alert
                  title="注意事项"
                  type="info"
                  description="此功能需要Chrome DevTools Protocol支持，请确保Chrome已启用远程调试端口。"
                  show-icon
                />
              </el-form-item>
              
              <el-form-item>
                <el-button 
                  type="primary" 
                  :disabled="!selectedWindows.length" 
                  :loading="executing" 
                  @click="keepOnlyCurrentTab"
                >
                  <el-icon><i-ep-document /></el-icon>
                  仅保留当前标签页
                </el-button>
                <el-button 
                  type="primary" 
                  :disabled="!selectedWindows.length" 
                  :loading="executing" 
                  @click="keepOnlyNewTab"
                >
                  <el-icon><i-ep-plus-document /></el-icon>
                  仅保留新标签页
                </el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>
      </el-tabs>
      
      <!-- 窗口选择面板 -->
      <div class="window-selection-panel">
        <h3>选择操作窗口</h3>
        <el-table
          v-loading="loading"
          :data="windows"
          @selection-change="handleSelectionChange"
          style="width: 100%"
          height="200"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="number" label="窗口编号" width="100" />
          <el-table-column prop="title" label="窗口标题" min-width="300" />
        </el-table>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Link, Edit, Document, DocumentAdd } from '@element-plus/icons-vue'

// 使用别名以避免命名冲突
const iEpLink = Link
const iEpEdit = Edit
const iEpDocument = Document
const iEpPlusDocument = DocumentAdd // 用DocumentAdd替代PlusDocument图标

interface ChromeWindow {
  id: number
  number: number
  title: string
}

interface QuickSite {
  name: string
  url: string
}

const windows = ref<ChromeWindow[]>([])
const selectedWindows = ref<ChromeWindow[]>([])
const loading = ref(false)
const executing = ref(false)

// 批量打开网页相关
const urlsInput = ref('')

const quickSites: QuickSite[] = [
  { name: 'Google', url: 'https://www.google.com' },
  { name: 'Twitter', url: 'https://twitter.com' },
  { name: 'Discord', url: 'https://discord.com' },
  { name: 'Gmail', url: 'https://mail.google.com' },
  { name: 'YouTube', url: 'https://www.youtube.com' },
  { name: 'GitHub', url: 'https://github.com' }
]

// 文本输入相关
const inputMode = ref<'text' | 'random'>('text')
const inputText = ref('')
const randomMin = ref(1000)
const randomMax = ref(9999)
const delayInput = ref(false)

// 计算属性
const hasValidUrls = computed(() => {
  const urls = urlsInput.value.split('\n').filter(url => url.trim())
  return urls.length > 0
})

const canExecuteInput = computed(() => {
  if (inputMode.value === 'text') {
    return inputText.value.trim() !== ''
  } else {
    return randomMin.value < randomMax.value
  }
})

// 导入窗口
const importWindows = async () => {
  loading.value = true
  try {
    const result = await window.electronAPI.getChromeWindows()
    windows.value = result
  } catch (error) {
    console.error('导入窗口失败:', error)
    ElMessage.error('导入窗口失败')
  } finally {
    loading.value = false
  }
}

// 处理选择变化
const handleSelectionChange = (selection: ChromeWindow[]) => {
  selectedWindows.value = selection
}

// 添加快速网站
const addQuickSite = (url: string) => {
  if (urlsInput.value) {
    urlsInput.value += '\n'
  }
  urlsInput.value += url
}

// 批量打开网页
const openWebpages = async () => {
  if (!selectedWindows.value.length || !hasValidUrls.value) return
  
  executing.value = true
  try {
    // 处理URLs
    const urls = urlsInput.value.split('\n')
      .map(url => url.trim())
      .filter(url => url)
    
    // 模拟在每个窗口打开网页
    for (const window of selectedWindows.value) {
      for (const url of urls) {
        // 这里将调用Electron API在Chrome窗口中打开网页
        await new Promise(resolve => setTimeout(resolve, 100))
      }
    }
    
    ElMessage.success(`已在 ${selectedWindows.value.length} 个窗口中打开网页`)
  } catch (error) {
    console.error('批量打开网页失败:', error)
    ElMessage.error('批量打开网页失败')
  } finally {
    executing.value = false
  }
}

// 执行文本输入
const executeTextInput = async () => {
  if (!selectedWindows.value.length || !canExecuteInput.value) return
  
  executing.value = true
  try {
    // 根据模式生成输入内容
    let inputContent = ''
    if (inputMode.value === 'text') {
      inputContent = inputText.value
    } else {
      // 生成随机数字
      const randomNum = Math.floor(Math.random() * (randomMax.value - randomMin.value + 1)) + randomMin.value
      inputContent = randomNum.toString()
    }
    
    // 模拟在每个窗口输入文本
    for (const window of selectedWindows.value) {
      // 这里将调用Electron API在Chrome窗口中输入文本
      await new Promise(resolve => setTimeout(resolve, delayInput.value ? 1000 : 100))
    }
    
    ElMessage.success(`已在 ${selectedWindows.value.length} 个窗口中执行文本输入`)
  } catch (error) {
    console.error('执行文本输入失败:', error)
    ElMessage.error('执行文本输入失败')
  } finally {
    executing.value = false
  }
}

// 仅保留当前标签页
const keepOnlyCurrentTab = async () => {
  if (!selectedWindows.value.length) return
  
  executing.value = true
  try {
    // 这里将调用Electron API通过CDP控制标签页
    await new Promise(resolve => setTimeout(resolve, 500))
    
    ElMessage.success(`已在 ${selectedWindows.value.length} 个窗口中保留当前标签页`)
  } catch (error) {
    console.error('保留当前标签页失败:', error)
    ElMessage.error('保留当前标签页失败')
  } finally {
    executing.value = false
  }
}

// 仅保留新标签页
const keepOnlyNewTab = async () => {
  if (!selectedWindows.value.length) return
  
  executing.value = true
  try {
    // 这里将调用Electron API通过CDP控制标签页
    await new Promise(resolve => setTimeout(resolve, 500))
    
    ElMessage.success(`已在 ${selectedWindows.value.length} 个窗口中保留新标签页`)
  } catch (error) {
    console.error('保留新标签页失败:', error)
    ElMessage.error('保留新标签页失败')
  } finally {
    executing.value = false
  }
}

onMounted(() => {
  importWindows()
})
</script>

<style lang="scss" scoped>
.batch-actions {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .tab-content {
    padding: 20px 0;
  }
  
  .form-hint {
    margin-top: 5px;
    font-size: 12px;
    color: #909399;
  }
  
  .quick-sites {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
  }
  
  .window-selection-panel {
    margin-top: 30px;
    border-top: 1px solid #ebeef5;
    padding-top: 20px;
    
    h3 {
      font-size: 16px;
      margin-bottom: 15px;
      color: #606266;
    }
  }
}
</style>